package com.manfred.JNDIStudy;

import java.io.Serializable;
import java.util.Hashtable;

import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.ldap.LdapContext;

public class Main {
	public static void main(String[] args) throws Exception {
		Hashtable<String, Object> env = new Hashtable<String, Object>();
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, "ldap://localhost:10389/o=JNDITutorial");
		// env.put(Context.SECURITY_PRINCIPAL, "joeuser");
		// env.put(Context.SECURITY_CREDENTIALS, "joepassword");
		Context ctx = new InitialContext(env);
		Object o = ctx.lookup("ou=People");
		System.out.println(o);
		LdapContext rl = (LdapContext) ctx.lookup("cn=Rosanna Lee,ou=People");
		System.out.println(rl.getNameInNamespace());
		NamingEnumeration<NameClassPair> list = ctx.list("ou=People");

		while (list.hasMore()) {
			NameClassPair nc = list.next();
			System.out.println(nc);
		}

		NamingEnumeration<Binding> bindings = ctx.listBindings("ou=People");

		while (bindings.hasMore()) {
			Binding bd = bindings.next();
			System.out.println(bd.getName() + ": " + bd.getObject());
		}

		// Create the object to be bound
		Fruit fruit = new Fruit("orange");

		// Perform the bind
		// ctx.bind("cn=Favorite Fruit", fruit);

		// Create the object to be bound
		Fruit fruit2 = new Fruit("lemon");

		// Perform the bind
		ctx.rebind("cn=Favorite Fruit", fruit2);

		// Remove the binding
		ctx.unbind("cn=Favorite Fruit");
		
		ctx.close();
	}

	static class Fruit implements Serializable {
		/**
		 * 
		 */
		private static final long serialVersionUID = -3477774964492215159L;
		String name;

		public Fruit(String name) {
			this.name = name;
		}
	}
}
